package com.ww.springboot.boot.thread.threadlocal;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-13 08:59
 */
public class ThreadLocalDemo内存泄露 {


    private static final ThreadLocal<String> threadLocal = new ThreadLocal();


    /**
     * 单线程的情况下 threadLocalMap 会跟着线程一起消亡
     * 即使key是弱引用,但是thread对threadLocalMap是强引用 因此GC不会回收其值
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        threadLocal.set("第一次设值");

        System.out.println("主线程获取:" + threadLocal.get());

       Thread thread =  new Thread(() -> {
            threadLocal.set("第二次子线程内设值");
            System.out.println("子线程获取:" + threadLocal.get());

            System.gc();
            System.out.println("--------子线程GC---------");
            System.out.println("子线程获取2:" + threadLocal.get());
        });
        thread.start();

//        Thread.sleep(1000);
//        System.out.println(thread.getName());

        System.out.println("主线程获取:" + threadLocal.get());
    }
}
